<?php
// +----------------------------------------------------------------------
// | QSCMS
// +----------------------------------------------------------------------
// | Copyright (c)  2025 https://www.qqss.net All rights reserved.
// +----------------------------------------------------------------------
// | Licensed QSCMS is not free software, commercial use must purchase official license from official website to avoid unnecessary legal disputes.
// +----------------------------------------------------------------------
// | Author: Contract 990504246@qq.com
// +----------------------------------------------------------------------

namespace app\common\plugin;

use support\Log;

/**
 * Main项目API服务
 * 用于调用main项目的API接口
 */
class MainApiService
{
    private $baseUrl;
    private $token;

    public function __construct()
    {
        $this->baseUrl = config('site.marketplace.main_api_url');
        if (!$this->baseUrl) {
            throw new \Exception('main_api_url 配置未设置');
        }

        // 确保URL以/结尾
        $this->baseUrl = rtrim($this->baseUrl, '/');
    }

    /**
     * 设置认证token
     */
    public function setToken($token)
    {
        $this->token = $token;
        return $this;
    }

    /**
     * 发送HTTP请求
     */
    private function request($method, $url, $data = null)
    {

        $headers = [
            'Content-Type: application/json',
            'Accept: application/json'
        ];

        // 如果有token，添加Bearer认证头（Sanctum格式）
        if ($this->token) {
            // $headers[] = 'Authorization: Bearer ' . $this->token;
            $data['token'] = $this->token;
        }
        // echo $this->baseUrl . $url;
        //     print_r($data);
        $ch = curl_init();
        curl_setopt_array($ch, [
            CURLOPT_URL            => $this->baseUrl . $url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT        => 30,
            CURLOPT_HTTPHEADER     => $headers,
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_SSL_VERIFYHOST => false,
        ]);

        if ($method === 'POST') {
            curl_setopt($ch, CURLOPT_POST, true);
            if ($data) {
                curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
            }
        }

        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $error    = curl_error($ch);
        curl_close($ch);

        if ($error) {
            Log::error('API请求失败', ['error' => $error, 'url' => $url]);
            throw new \Exception('API请求失败: ' . $error);
        }

        $result = json_decode($response, true);
        if (json_last_error() !== JSON_ERROR_NONE) {
            Log::error('API响应解析失败', ['response' => $response, 'url' => $url]);
            throw new \Exception('API响应解析失败');
        }

        if ($httpCode >= 400) {
            Log::error('API请求错误', ['code' => $httpCode, 'response' => $result, 'url' => $url]);
            throw new \Exception($result['message'] ?? $result['msg'] ?? 'API请求失败');
        }

        Log::info('API请求成功', ['url' => $url, 'response' => $result]);
        return $result;
    }

    /**
     * 用户登录
     */
    public function login($email, $password)
    {
        $response = $this->request('POST', '/api/service/login', [
            'email'    => $email,
            'password' => $password
        ]);

        if ($response['code']) {
            $this->setToken($response['data']['token']);
            return $response['data'];
        }

        throw new \Exception($response['message'] ?? '登录失败');
    }

    /**
     * 获取插件列表
     */
    public function getPlugins($params = [])
    {
        $query = http_build_query($params);
        $url   = '/api/service/plugins' . ($query ? '?' . $query : '');



        $response = $this->request('GET', $url);

        if (isset($response['code']) && $response['code'] === true) {
            return $response['data'];
        }

        throw new \Exception($response['message'] ?? '获取插件列表失败');
    }

    /**
     * 获取插件详情
     */
    public function getPlugin($id)
    {
        $url = "/api/service/plugins/{$id}";

        $response = $this->request('GET', $url);

        if (isset($response['code']) && $response['code'] === true) {
            return $response['data'];
        }

        throw new \Exception($response['message'] ?? '获取插件详情失败');
    }

    /**
     * 获取模板列表
     */
    public function getTemplates($params = [])
    {
        $query = http_build_query($params);
        $url   = '/api/service/templates' . ($query ? '?' . $query : '');

        $response = $this->request('GET', $url);

        if ($response['code']) {
            return $response['data'];
        }

        throw new \Exception($response['message'] ?? '获取模板列表失败');
    }

    /**
     * 获取分类列表
     */
    public function getCategories($type = null)
    {
        $url = "/api/service/categories";
        if ($type) {
            $url .= "?type={$type}";
        }

        $response = $this->request('GET', $url);

        if ($response['code']) {
            return $response['data'];
        }

        throw new \Exception($response['message'] ?? '获取分类列表失败');
    }

    /**
     * 获取用户插件
     */
    public function getUserPlugins()
    {
        if (!$this->token) {
            throw new \Exception('需要登录');
        }

        $response = $this->request('GET', '/api/service/user/plugins');

        if ($response['code']) {
            return $response['data'];
        }

        throw new \Exception($response['message'] ?? '获取用户插件失败');
    }

    /**
     * 获取用户模板
     */
    public function getUserTemplates()
    {
        if (!$this->token) {
            throw new \Exception('需要登录');
        }

        $response = $this->request('GET', '/api/service/user/templates');

        if ($response['code']) {
            return $response['data'];
        }

        throw new \Exception($response['message'] ?? '获取用户模板失败');
    }

    /**
     * 下载插件
     */
    public function downloadPlugin($id, $licenseType = 'basic')
    {
        if (!$this->token) {
            throw new \Exception('需要登录');
        }

        $response = $this->request('GET', "/api/service/download/plugin/{$id}");

        if (isset($response['code']) && $response['code'] === true) {
            return $response['data'];
        }

        throw new \Exception($response['message'] ?? '下载插件失败');
    }

    /**
     * 下载模板
     */
    public function downloadTemplate($id)
    {
        if (!$this->token) {
            throw new \Exception('需要登录');
        }

        $response = $this->request('GET', "/api/service/download/template/{$id}");

        if ($response['code']) {
            return $response['data'];
        }

        throw new \Exception($response['message'] ?? '下载模板失败');
    }

    /**
     * 下载文件到本地
     */
    public function downloadFile($downloadUrl, $savePath)
    {
        $ch = curl_init();
        curl_setopt_array($ch, [
            CURLOPT_URL            => $downloadUrl,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT        => 300, // 5分钟超时
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_SSL_VERIFYHOST => false,
        ]);

        if ($this->token) {
            curl_setopt($ch, CURLOPT_HTTPHEADER, [
                'Authorization: Bearer ' . $this->token
            ]);
        }

        $fileContent = curl_exec($ch);
        $httpCode    = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $error       = curl_error($ch);
        curl_close($ch);

        if ($error) {
            throw new \Exception('文件下载失败: ' . $error);
        }

        if ($httpCode !== 200) {
            throw new \Exception('文件下载失败: HTTP ' . $httpCode);
        }

        // 确保目录存在
        $dir = dirname($savePath);
        if (!is_dir($dir)) {
            mkdir($dir, 0755, true);
        }

        if (file_put_contents($savePath, $fileContent) === false) {
            throw new \Exception('文件保存失败');
        }

        return true;
    }

    /**
     * 解压ZIP文件
     */
    public function extractZip($zipPath, $extractPath)
    {
        if (!class_exists('ZipArchive')) {
            throw new \Exception('ZipArchive扩展未安装');
        }

        $zip    = new \ZipArchive();
        $result = $zip->open($zipPath);

        if ($result !== TRUE) {
            throw new \Exception('无法打开ZIP文件: ' . $result);
        }

        // 确保解压目录存在
        if (!is_dir($extractPath)) {
            mkdir($extractPath, 0755, true);
        }

        $result = $zip->extractTo($extractPath);
        $zip->close();

        if (!$result) {
            throw new \Exception('ZIP文件解压失败');
        }

        return true;
    }

    /**
     * 创建支付订单
     */
    public function createPaymentOrder($params)
    {
        if (!$this->token) {
            throw new \Exception('需要登录');
        }

        $response = $this->request('POST', '/api/payment/create-order', $params);

        if ($response['success'] === true || $response['success'] === 1) {
            return $response['data'];
        }

        throw new \Exception($response['message'] ?? '创建订单失败');
    }

    /**
     * 检查支付状态
     */
    public function checkPaymentStatus($params)
    {
        if (!$this->token) {
            throw new \Exception('需要登录');
        }

        $response = $this->request('POST', '/api/payment/query-order', $params);

        // print_r($response);

        if ($response['success'] === true || $response['success'] === 1) {
            return $response['data'];
        }

        throw new \Exception($response['message'] ?? '查询支付状态失败');
    }
}
